var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var version = require('../../config/version.js');
var date_util = require('../../utils/date_util.js');
var user = require('../../services/user.js');
var event = require('../../utils/event.js');
var app = getApp();
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'

Page({
  data: {
    navigationBarTitle: '同感 • 想去',
    navigationBarHeight,
    tabbar: {},
    isIphoneX: app.globalData.isIphoneX ? true : false,
    id: 1005007,
    scrollLeft: 0,
    scrollTop: 0,
    scrollHeight: 0,
    systemInfo: {},
    page: 1,
    size: 10000,
    start_activies: [],
    end_activies: [],
    not_activies: [],
    userInfo: app.globalData.userInfo,
    auth: app.globalData.auth,
    hasPhone: app.globalData.hasPhone,
    showPage: false,
    selectedFlag: [],
    lastid: '',
    lasttimestamp: 0,
  },
  onLoad: function(options) {
    wx.hideTabBar();
    app.editTabbar();
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scrollHeight: res.windowHeight,
          systemInfo: res
        });
      }
    });

  },
  showLoadTip: function() {
    wx.showLoading({
      title: '正在加载中...',
      mask: true
    })
  },
  onMyevent: function(e) {
    this.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone
    })
    //权限控制完成后，再次调用业务代码
    if (this.data.auth && this.data.hasPhone) {
      this.GetMyFollowActivities()
      event.emit('AuthChanged');
    }
  },

  onReady: function() {},
  onShow: function() {
    var that = this
    that.setData({
      userInfo: app.globalData.userInfo,
      auth: app.globalData.auth,
      hasPhone: app.globalData.hasPhone,
    })
    if (that.data.auth && that.data.hasPhone) {   
      that.GetMyFollowActivities()
    } else {
      //else
      that.auth = that.selectComponent("#auth");
      util.getScope('scope.userInfo').then(function(resss) {
        if (resss) {
          that.auth.hideAuth();
          ///防止緩存失效带来的问题
          let code = null;
          return that.login().then((res) => { //userInfo
            code = res.code;
            wx.getUserInfo({
              withCredentials: true,
              success: function(res_user) {
                //先去登陆        
                wx.request({
                  url: api.userAuth,
                  data: {
                    platform: 'wx',
                    authorizationCode: code,
                    userEncryptrfData: res_user.encryptedData,
                    iv: res_user.iv
                  },
                  method: 'POST',
                  header: {
                    'Content-Type': 'application/json',
                    'accessToken': wx.getStorageSync('token'),
                    'appVersion': version.appVersion,
                    'deviceModel': getApp().globalData.systemInfo.model,
                    'platform': 'wx',
                    'build': version.build,
                    'deviceMachineCode': '',
                    'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                    'deviceOSVersion': getApp().globalData.systemInfo.system,
                  },
                  success: function(res) {
                    if (res && res.statusCode == 200 && res.data.code == 200) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      var userInfo = res.data.data.user
                      if (userInfo && !userInfo.avatarUrl) {
                        userInfo.avatarUrl = version.defaultAvataUrl
                      }
                      wx.setStorageSync('userInfo', userInfo);
                      app.globalData.userInfo = userInfo
                      app.globalData.hasUserInfo = true
                      app.globalData.auth = true
                      app.globalData.hasPhone = true
                      wx.setStorageSync('hasPhone', true);
                      wx.setStorageSync('auth', true);
                      that.setData({
                        auth: true,
                        userInfo: app.globalData.userInfo,
                        hasPhone: app.globalData.hasPhone,
                      });
                      that.GetMyFollowActivities()
                    }
                    if(res && res.data.code==301){
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      app.globalData.hasPhone = false
                      wx.setStorageSync('hasPhone', false);
                      that.setData({
                        hasPhone: false,
                      });
                      that.auth.showAuth();
                    }
                  }
                })
              }
            })
          })
          //防止緩存失效带来的问题
        } else {
          that.auth.showAuth();
        }
      })
      //else
    }
  },
  onHide: function() {},
  onUnload: function() {},
  login: function() {
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            //登录远程服务器
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },

  dealData: function(act, type) {
    var that = this
    var newAct = []
    if (act.length > 0) {
      for (var i = 0; i < act.length; i++) {
        var activity = act[i].activity
        activity.titleStr = activity.name.length > 41 ? activity.name.substr(0, 38) + '...' : activity.name;
        //处理新动态
        var flowersPhoto = []
        if (act[i].activieUsers && act[i].activieUsers.length > 3) { //开始取前三个头像
          flowersPhoto = act[i].activieUsers.slice(0, 3)
        } else {
          flowersPhoto = act[i].activieUsers
        }
        act[i].followers = flowersPhoto;

        activity.acti_photo = activity.coverUrl +"?imageMogr2/thumbnail/" +
          370 +
          "x" +
          "/format/jpg/size-limit/80k!";
        activity.commentCount = act[i].feelingCount

        // 获取结束活动的最后一条uuid 和 begin_time
        if (type == 2) {
          let one_act = act[act.length - 1]
          that.setData({
            lastid: one_act.activity.id,
            lasttimestamp: one_act.activity.beginTime
          })
        }
        // 处理没开始的剩余时间问题
        if (type == 3) {
          activity.rest = date_util.getRemainderTime(activity.beginTime)
        }

        newAct.push(activity)
      }
    }
    return newAct;
  },

  GetMyFollowActivities: function() {
    var that = this
    if (that.data.auth && that.data.hasPhone) {
      that.showLoadTip()
      util.pututrequest(api.memoryFirstPage + '?userId=' + that.data.userInfo.id, 'GET', {}).then(res => {
        if (res && res.code == 200) {
          var one = that.dealData(res.data.onGoing, 1)
          var two = that.dealData(res.data.end, 2)
          var three = that.dealData(res.data.notStart, 3)
          that.setData({
            start_activies: one,
            end_activies: two,
            not_activies: three,
            showPage: true,
          })
          wx.hideLoading()
        }
      })
    }
  },

  // 获取结束的下一页活动
  GetNextPageActivity: function() {
    var that = this
    if (that.data.auth && that.data.hasPhone) {
      that.showLoadTip()
      util.pututrequest(api.memoryListNew + '?userId=' + that.data.userInfo.id + '&lastId=' + that.data.lastid + '&lastTimestamp=' + that.data.lasttimestamp, 'GET').then(res => {
        if (res && res.code == 200) {
          var next_page = that.dealData(res.data, 2)
          var end_new = that.data.end_activies.concat(next_page)
          that.setData({
            end_activies: end_new
          })
          wx.hideLoading()
        }
      })
    }
  },

  followApp: function() {
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人，很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧！'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人，请到AppStore里下载同感App查看更多同感动态！'
          })
        }
      }
    })
  },

  // 展开折叠选择  
  changeToggle: function(e) {
    var index = e.currentTarget.dataset.index;
    if (this.data.selectedFlag[index]) {
      this.data.selectedFlag[index] = false;
    } else {
      this.data.selectedFlag[index] = true;
    }
    this.setData({
      selectedFlag: this.data.selectedFlag
    })
  },

  goUpload: function(e) {
    var that = this;
    if (!that.data.isShowDate) {
      wx.navigateTo({
        url: '/pages/search/search',
        success: function() {},
        fail: function() {},
        complete: function() {}
      })
    }
  },
  onPullDownRefresh() {
    var that = this
    that.GetMyFollowActivities();
    wx.stopPullDownRefresh();
  },
  onReachBottom() {
    var that = this
    that.GetNextPageActivity();
  },


})